//
// Created by 段大志 on 16/4/23.
// Copyright (c) 2016 BMProject. All rights reserved.
//

#import "BackgroundBizVc.h"
#import "BaseTableView.h"
#import "CommonSearchBar.h"
#import "UIViewController+common.h"
#import "UIColor+Extension.h"
#import "BackgroundBizCell.h"
#import "DataModel.h"
#import "BackgroundDispalyVc.h"
#import "BackgroundDealVc.h"

@interface BackgroundBizVc() <UITableViewDelegate, UITableViewDataSource,UISearchBarDelegate> {
    BlackListWrapModel*_listWrapModel;
    NSString *_title;//搜索用的title 一开始为空
}
@property (strong, nonatomic) CommonSearchBar *searchBar;
@property(strong, nonatomic)  BaseTableView *tableView;
@property(nonatomic, assign) int page;//某些请求数据有页码的页面用到的参数
@end

@implementation BackgroundBizVc {

}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog(@"--后台业务列表--");
    NAV_INIT(self, @"后台业务列表", @"back", @selector(backButtonClick:), @"", nil);
    [self intSearBar];
    [self initTab];
    [self.tableView.header beginRefreshing];
}

- (void) intSearBar {
    self.searchBar = [[CommonSearchBar alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 40 )];
    [self.view addSubview:self.searchBar];
    self.searchBar.delegate = self;
    self.searchBar.placeholder = @"后台业务列表";
}

- (void)initTab {
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(
            0,
            50,
            UIScreenWidth,
            UIScreenHeight - 64 - 50) style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor backgroundColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.tableFooterView.backgroundColor = [UIColor backgroundColor];
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        self.page = 1;
        _title = @"";//置空
        DLog(@"开始请求......");
        [self requestList_blackList];
    }];
    [self.tableView addFooterRefreshTarget:self action:@selector(requestLoadMoreDataByPage)];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}


#pragma mark  ------- UITableView UITableViewDelegate or UITableViewDataSource---------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return (_listWrapModel == nil ? 0 : (_listWrapModel.blackListModels == nil ? 0 : _listWrapModel.blackListModels.count));
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150 + 10;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BackgroundBizCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BackgroundBizCell"];
    if (!cell)
        cell = [[[UINib nibWithNibName:@"BackgroundBizCell" bundle:nil] instantiateWithOwner:self options:nil] lastObject];
    [cell setCellInfo:_listWrapModel andPosition:indexPath.row];
    cell.dealBtn.tag = indexPath.row;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell.dealBtn    addTarget:self action:@selector(dealActions:)    forControlEvents:UIControlEventTouchUpInside];
    [cell.previewBtn addTarget:self action:@selector(previewActions:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}

#pragma mark --- 预览 ---
- (void)previewActions:(UIButton *)sender {
    DLog(@" --- 预览 ---");
    BackgroundDispalyVc *dispalyVc = [[BackgroundDispalyVc alloc] init];
    dispalyVc.blackListWrapModel   = _listWrapModel;
    dispalyVc.position             = sender.tag;
    [self.navigationController pushViewController:dispalyVc animated:YES];
}

#pragma mark --- 处理 ---
- (void)dealActions:(UIButton *)sender {
    DLog(@"--- 处理 ---");
    BackgroundDealVc *dispalyVc    = [[BackgroundDealVc alloc] init];
    dispalyVc.blackListWrapModel   = _listWrapModel;
    dispalyVc.position             = sender.tag;
    [dispalyVc setBlock:^(BOOL isDeal) {
        if (isDeal) {
            self.page = 1;
            _title = @"";//置空
            [self.tableView.header beginRefreshing];
        }
    }];
    [self.navigationController pushViewController:dispalyVc animated:YES];
}

#pragma mark ------ UISearchBarDelegate-------------------
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    [self.searchBar setCancelButtonTitle:@"取消"];
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    _title = self.searchBar.text;
    self.page = 1;
    [self requestList_blackList];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
}



#pragma mark 底部刷新
- (void)requestLoadMoreDataByPage {
    self.page++;
    [self requestList_blackList];
}

#pragma mark 请求数据

- (void)requestList_blackList {
    [UserServices blackListByToken:[[AppDelegate appDelegate] getUserInfo].token
                             title:_title
                         recUserId:@""
                            userId:@""
                              page:kIntToString(self.page)
                          pageSize:@"9999999"
                        showDialog:YES
                   completionBlock:^(int result, id responseObject) {
                        if (result == API_Request_Success) {
                            NSMutableArray *array = responseObject;
                            if (self.page == 1) {
                                [self.tableView.footer resetNoMoreData];//重置有更多数据
                                if (array == nil || array.count == 0) {
                                    //提示无数据
                                    [SVProgressHUD showErrorWithStatus:@"查无数据"];
                                } else {
                                    for (int i = 0; array && i < array.count && i == 0; ++i) {
                                        BlackListWrapModel *blackListWrapModel = [[BlackListWrapModel alloc] init];

                                        NSMutableArray *dict = [[NSMutableArray alloc] initWithCapacity:array.count-1];
                                        for (int j = 0; j < array.count - 1; ++j) {
                                            [dict addObject:array[j]];
                                        }

                                        NSArray *array1     = array[ array.count-1];

                                        NSMutableArray *array2 = [NSMutableArray array];
                                        blackListWrapModel.dictionary = dict;
                                        if (array1 && array1.count > 0) {
                                            for (int k = 0; k < array1.count; ++k) {
                                                [array2 addObject:[[BlackListModel alloc] initWithDictionary:array1[k] error:nil]];
                                            }
                                        }
                                        blackListWrapModel.blackListModels = array2;

                                       _listWrapModel = blackListWrapModel;
                                        [self.tableView reloadData];
                                    }
                                }
                            }
                            if (array.count == 0) {
                                self.page--;
                            }
                            [self.tableView.header endRefreshing];
                            [self.tableView.footer endRefreshing];
                            [self.tableView reloadData];
                            if (array.count < kListPageSize)
                                [self.tableView.footer noticeNoMoreData];//没有更多数据
                        } else {//出错时的处理
                            //提示出错
                            [SVProgressHUD showErrorWithStatus:Error_Format];
                        }
                   }];
}



@end